package middlewares

import (
	"example.com/myproject/project/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

// 第一版拦截器
func AuthMiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Token")
		if token == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "No Login"})
			c.Abort()
			return
		}
		if token == "test" {
			c.Next()
			return
		}
		name, err := utils.ParseJWT(token)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
			c.Abort()
			return
		}
		c.Set("username", name)
		c.Next()
	}
}

// 第二版拦截器
func CheckMiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Token")
		if token == "test" {
			c.Next()
			return
		}
		if true == true { //config.WebServer.Tokens[token]
			c.Next()
		} else {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Undefined Token"})
		}
	}
}

func TCPMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取客户端的 Token
		token := c.GetHeader("token")
		fmt.Println(token)
		if token == "test" {
			c.Next()
			return
		}
		if token == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未授权的连接"})
			c.Abort()
			return
		}
		c.Next()
	}
}
